<template>
  <div class="data-table-container">
    <div class="table-header">
      <h3>{{ title }}</h3>
      <div class="table-actions">
        <el-input
          v-if="showSearch"
          v-model="searchText"
          placeholder="搜索..."
          prefix-icon="Search"
          clearable
          @input="handleSearch"
          style="width: 200px;"
        />
        <el-button v-if="showRefresh" type="primary" :icon="Refresh" circle @click="$emit('refresh')" />
      </div>
    </div>
    
    <el-table 
      :data="filteredItems" 
      border 
      style="width: 100%"
      empty-text="暂无数据"
      :max-height="maxHeight"
      v-loading="loading"
    >
      <el-table-column 
        v-for="column in displayColumns" 
        :key="column.prop"
        :prop="column.prop"
        :label="column.label"
        :width="column.width"
        :formatter="column.formatter"
      >
        <template #default="scope" v-if="column.slot">
          <slot :name="column.prop" :row="scope.row" :$index="scope.$index">
            {{ scope.row[column.prop] }}
          </slot>
        </template>
      </el-table-column>
    </el-table>
    
    <div class="table-footer" v-if="showPagination && filteredItems.length > 0">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalItems"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        prev-text="上一页"
        next-text="下一页"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { Search, Refresh } from '@element-plus/icons-vue'

interface Column {
  prop: string
  label: string
  width?: string | number
  formatter?: (row: any, column: any, cellValue: any, index: number) => any
  slot?: boolean
}

const props = defineProps({
  items: {
    type: Array as () => Array<Record<string, any>>,
    default: () => []
  },
  columns: {
    type: Array as () => Column[],
    default: () => []
  },
  title: {
    type: String,
    default: '数据列表'
  },
  showSearch: {
    type: Boolean,
    default: true
  },
  showRefresh: {
    type: Boolean,
    default: true
  },
  showPagination: {
    type: Boolean,
    default: true
  },
  maxHeight: {
    type: [String, Number],
    default: '500px'
  },
  loading: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['refresh', 'page-change', 'size-change'])

const searchText = ref('')
const currentPage = ref(1)
const pageSize = ref(10)

// 如果没有提供列定义，则自动生成
const displayColumns = computed(() => {
  if (props.columns.length > 0) return props.columns
  
  if (!props.items.length) return []
  
  // 自动生成列定义
  return Object.keys(props.items[0])
    .filter(key => !key.startsWith('_')) // 过滤掉以下划线开头的属性
    .map(key => {
      // 将驼峰命名转换为中文标签
      const label = key
        .replace(/([A-Z])/g, ' $1')
        .replace(/^./, str => str.toUpperCase())
        .replace(/Id$/, 'ID')
        .replace(/Num$/, '数量')
        .replace(/Count$/, '计数')
        .replace(/Name$/, '名称')
        .replace(/Time$/, '时间')
        .replace(/Date$/, '日期')
      
      return {
        prop: key,
        label: label,
        width: key.includes('Time') || key.includes('Date') ? 180 : undefined
      }
    })
})

// 过滤和分页
const filteredItems = computed(() => {
  let result = [...props.items]
  
  // 搜索过滤
  if (searchText.value) {
    const searchLower = searchText.value.toLowerCase()
    result = result.filter(item => {
      return Object.values(item).some(val => 
        val !== null && 
        val !== undefined && 
        String(val).toLowerCase().includes(searchLower)
      )
    })
  }
  
  // 分页
  if (props.showPagination) {
    const start = (currentPage.value - 1) * pageSize.value
    const end = start + pageSize.value
    return result.slice(start, end)
  }
  
  return result
})

const totalItems = computed(() => {
  if (searchText.value) {
    return filteredItems.value.length
  }
  return props.items.length
})

// 重置分页
watch(() => props.items, () => {
  currentPage.value = 1
})

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
}

// 分页处理
const handleSizeChange = (size: number) => {
  pageSize.value = size
  emit('size-change', size)
}

const handleCurrentChange = (page: number) => {
  currentPage.value = page
  emit('page-change', page)
}
</script>

<style scoped>
.data-table-container {
  margin-top: 20px;
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.table-header h3 {
  margin: 0;
  font-size: 18px;
  color: #303133;
}

.table-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

.table-footer {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}

@media (max-width: 768px) {
  .table-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .table-actions {
    width: 100%;
  }
}
</style>
